﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Engine.Dtd.Schema {
    public sealed partial class DModelGroups {
        internal class Iterator : IEnumerator<DElement> {
            private DModelGroups root;
            private IModelGroupsNode current;

            public Iterator(DModelGroups group) {
                Debug.Assert(group != null);
                this.root = group;
                this.current = root;
                }

            public DElement Current {
                get { return current as DElement; }
                }

            public void Dispose() {
                root = null;
                current = null;
                }

            object System.Collections.IEnumerator.Current {
                get { return current; }
                }

            public bool MoveNext() {
                if (current == null)
                    return false;
                IModelGroupsNode next = current.FirstItem;
                if (next == null)
                    next = current.NextItem();
                if (next == null) {
                    IModelGroupsNode parent = current.Parent;
                    while (parent != root.parent) {
                        next = parent.NextItem();
                        if (next == null)
                            parent = parent.Parent;
                        else
                            break;
                        }
                    if (next == null) {
                        current = null;
                        return false;
                        }
                    }
                while (next.IsModelGroups()) {
                    next = next.FirstItem;
                    }
                current = next;
                return true;
                }

            public void Reset() {
                if (current.Parent == null)
                    return;
                while (current.Parent != root) {
                    current = current.Parent;
                    }
                }
            }
        }
    }
